<template>
	<view class="order-page">
		<view class="order-form-container">
			<view class="order-form">
				<!-- 订单号 -->
				<view class="product-item-row">
					<view>订单号：</view>
					<uni-easyinput v-model="orderNumber" placeholder="请输入订单号" readonly />
				</view>
				<!-- 订单时间 -->
				<view class="product-item-row">
					<view>时间：</view>
					<uni-datetime-picker type="date" :clear-icon="false" placeholder="请选择订单时间" v-model="orderTime" />
				</view>
				<!-- 客户名称 -->
				<view class="product-item-row">
					<view>客户：</view>
					<picker mode="selector" :range="customerNames" @change="onCustomerChange" :value="customerIndex">
						<view class="pickercustomer">{{ customerNames[customerIndex] || '请选择客户' }}</view>
					</picker>
				</view>
				<!-- 产品清单 -->
				<view class="product-list-header">
					<view>产品清单</view>
					<button type="primary" @click="addProduct" class="add-product-button">+添加产品</button>
				</view>
				<view class="product-list">
					<view v-for="(product, index) in orderProducts" :key="index" class="product-item">
						<view class="product-item-row">
							<view>产品：</view>
							<picker mode="selector" :range="productNames" @change="onProductChange(index, $event)"
								:value="product.productIndex">
								<view class="pickerproduct">{{ productNames[product.productIndex] || '请选择产品' }}</view>
							</picker>
						</view>
						<view class="product-item-row">
							<view>条码：</view>
							<view class="picker-view">{{ product.no }}</view>
						</view>
						<view class="product-item-row">
							<view>规格：</view>
							<view class="picker-view">{{ product.standard }}</view>
						</view>
						<view class="product-item-row">
							<view>库存：</view>
							<view class="picker-view">{{ product.stock }}</view>
						</view>
						<view class="product-item-row">
							<view>数量：</view>
							<view class="picker">
								<input class="uni-input" type="digit" v-model.number="product.count" placeholder="请输入数量"
									@input="calculateAmount(index)" />
							</view>
						</view>
						<view class="product-item-row">
							<view>单价：</view>
							<view class="picker">
								<input class="uni-input" type="digit" v-model.number="product.productPrice"
									placeholder="请输入单价" @input="calculateAmount(index)" />
							</view>
						</view>
						<view class="product-item-row">
							<view>金额：</view>
							<view class="picker-view">{{ product.amount }}</view>
						</view>
						<view class="product-item-row">
							<view>税率：</view>
							<view class="picker">
								<input class="uni-input" type="digit" v-model.number="product.taxPercent"
									placeholder="请输入税率" />
							</view>
						</view>
						<view class="product-item-row">
							<view>备注：</view>
							<uni-easyinput type="textarea" autoHeight v-model="product.remark"
								placeholder="请输入备注"></uni-easyinput>
						</view>
						<view class="product-item-row">
							<button type="warn" size="mini" @click="removeProduct(index)"
								class="delete-button">删除产品</button>
						</view>
					</view>
				</view>
				<!-- 定金金额 -->
				<view class="product-item-row">
					<view>定金：</view>
					<view class="picker">
						<input class="uni-input" type="digit" v-model.number="depositPrice" placeholder="请输入定金金额" />
					</view>
				</view>
				<!-- 附件地址 -->
				<view class="product-item-row">
					<view>附件：</view>
					<uni-file-picker ref="filePicker" v-model="fileList" file-mediatype="all" mode="grid"
						  @select="filePicker" />
					<view v-if="fileUrl">已上传文件路径：{{ fileUrl }}</view>
				</view>
				<!-- 备注 -->
				<view class="product-item-row">
					<view>备注：</view>
					<uni-easyinput type="textarea" autoHeight v-model="remark" placeholder="请输入备注"></uni-easyinput>
				</view>
				<button type="primary" @click="submitOrder" class="submit-button" :disabled="isSubmitting">提交订单</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getCustomers,
		getProducts,
		getProductCount,
		updateSaleOrder,
		createSaleOrder,
		getOrderDetails
	} from "@/sheep/api/erp/order.js";
	import {
		uploadFile
	} from "@/api/system/upoad.js";
	export default {
		data() {
			return {
				orderId: "",
				isEdit: false, // 是否为编辑模式
				orderNumber: "",
				orderTime: "",
				customerIndex: -1,
				customerNames: [],
				customers: [],
				saleUserId: null,
				accountId: null,
				discountPercent: 0,
				depositPrice: 0,
				fileUrl: "",
				fileList: [],
				remark: "",
				orderProducts: [],
				productNames: [],
				products: [],
				isSubmitting: false, // 防止重复提交
			};
		},
		methods: {
			setPageTitle() {
				const title = this.isEdit ? "修改销售订单" : "新增销售订单";
				uni.setNavigationBarTitle({
					title,
				});
			},
			async filePicker(file) {
			//	debugger
				if (!file || !file.tempFilePaths.length) {
					this.showToast("请选择文件");
					return;
				} 
				console.log(file.tempFiles[0].file)
				console.log(file.tempFilePaths[0])
				const dataFile = {file: file.tempFiles[0].file, path: file.tempFilePaths[0]}
				try {
					const res = await uploadFile(dataFile); // 调用上传接口
					this.fileUrl = res.data.url; // 设置上传后的文件路径
					this.showToast("文件上传成功", "success");
				} catch (error) {
					this.showToast("文件上传失败");
				}
			},
			showToast(message, type = "none") {
				uni.showToast({
					title: message,
					icon: type,
				});
			},
			async fetchOrderDetails() {
				try {
					const res = await getOrderDetails(this.orderId);
					const order = res.data;
					this.orderNumber = order.no;
					this.orderTime = new Date(order.orderTime).toISOString().split('T')[0];
					this.customerIndex = this.customers.findIndex(cust => cust.id === order.customerId);
					this.depositPrice = order.depositPrice;
					this.fileUrl = order.fileUrl || "无附件";
					this.remark = order.remark || "无备注";

					// 映射产品数据
					this.orderProducts = order.items.map((item) => {
						console.log(item)
						const productIndex = this.products.findIndex(product => product.id === item.productId);
						return {
							id: item.productId,
							name: item.productName,
							no: item.productBarCode,
							standard: item.standard,
							stock: item.stockCount,
							count: item.count,
							productPrice: item.productPrice || 0,
							amount: ((item.count || 0) * (item.productPrice || 0)).toFixed(2),
							taxPercent: item.taxPercent,
							remark: item.remark || "无备注",
							productIndex,
						};
					});
				} catch (error) {
					this.showToast("获取订单详情失败");
				}
			},
			async fetchCustomers() {
				try {
					const res = await getCustomers();
					this.customers = res.data;
					this.customerNames = res.data.map(customer => customer.name);
				} catch (error) {
					this.showToast("获取客户数据失败");
				}
			},
			async fetchProducts() {
				try {
					const res = await getProducts();
					this.products = res.data;
					this.productNames = res.data.map(product => product.name);
				} catch (error) {
					this.showToast("获取产品数据失败");
				}
			},
			onCustomerChange(e) {
				this.customerIndex = parseInt(e.detail.value, 10);
				if (this.customerIndex !== -1) {
					this.saleUserId = this.customers[this.customerIndex].saleUserId;
				}
			},
			async onProductChange(index, e) {
				const productIndex = parseInt(e.detail.value, 10);
				const selectedProduct = this.products[productIndex];
				console.log(selectedProduct)
				try {
					const res = await getProductCount({
						productId: selectedProduct.id
					});
					this.$set(this.orderProducts, index, {
						...this.orderProducts[index],
						productIndex,
						id: selectedProduct.id,
						name: selectedProduct.name,
						no: selectedProduct.no,
						standard: selectedProduct.standard,
						stock: res.data,
						productPrice: selectedProduct.salePrice,
						remark: selectedProduct.remark,
					});
				} catch (error) {
					this.showToast("获取库存失败");
				}
			},
			addProduct() {
				this.orderProducts.push({
					productIndex: -1,
					id: "",
					name: "",
					no: "",
					stock: 0,
					standard: "",
					count: 0,
					productPrice: 0,
					amount: "0.00",
					taxPercent: 0,
					remark: "",
				});
			},
			removeProduct(index) {
				this.orderProducts.splice(index, 1);
			},
			calculateAmount(index) {
				const product = this.orderProducts[index];
				const count = parseFloat(product.count);
				const productPrice = parseFloat(product.productPrice);
				if (!isNaN(count) && !isNaN(productPrice)) {
					product.amount = (count * productPrice).toFixed(2);
				} else {
					product.amount = "0.00";
				}
			},
			async submitOrder() {
				if (this.isSubmitting) return;
				this.isSubmitting = true;

				if (!this.orderNumber || this.customerIndex === -1 || this.orderProducts.length === 0) {
					this.showToast("请填写完整订单信息");
					this.isSubmitting = false;
					return;
				}

				for (let i = 0; i < this.orderProducts.length; i++) {
					const product = this.orderProducts[i];
					if (product.count <= 0 || product.productPrice <= 0) {
						this.showToast(`请填写第 ${i + 1} 个产品的数量和单价`);
						this.isSubmitting = false;
						return;
					}
				}

				const timestamp = new Date(this.orderTime).getTime();
				if (isNaN(timestamp)) {
					this.showToast("订单时间格式不正确");
					this.isSubmitting = false;
					return;
				}

				const updatedOrder = {
					id: this.orderId,
					no: this.orderNumber,
					customerId: this.customers[this.customerIndex].id,
					orderTime: timestamp,
					items: this.orderProducts.map(item => ({
						productId: item.id,
						count: item.count,
						productPrice: item.productPrice,
						taxPercent: item.taxPercent,
						remark: item.remark,
					})),
					depositPrice: this.depositPrice,
					fileUrl: this.fileUrl,
					remark: this.remark,
				};

				try {
					if (this.isEdit) {
						await updateSaleOrder(updatedOrder);
					} else {
						await createSaleOrder(updatedOrder);
					}
					this.showToast("订单提交成功", "success");
					uni.navigateBack();
				} catch (error) {
					console.log("error", error);
					this.showToast("订单提交失败:" + error.msg);
				} finally {
					this.isSubmitting = false;
				}
			},

			showToast(message, type = "none") {
				uni.showToast({
					title: message,
					icon: type,
				});
			},
		},
		onLoad() {
			this.orderId = uni.getStorageSync('orderId');
			this.isEdit = !!this.orderId; // 如果有 productId，则为编辑模式
			this.setPageTitle(); // 设置页面标题
			this.fetchCustomers();
			this.fetchProducts();
			if (this.orderId) {
				this.fetchOrderDetails();
			} else {
				this.orderTime = new Date().toISOString().split("T")[0];
			}
		},
	};
</script>


<style scoped>
	/* 样式与之前相同 */
	.order-page {
		padding: 10px;
		background-color: #f5f5f5;
	}

	.order-form-container {
		/* 为顶部导航栏留出空间 */
		padding: 10px;
		background-color: #fff;
		border-radius: 10px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.order-form {
		display: flex;
		flex-direction: column;
		gap: 8px;
	}

	.form-input {
		flex-grow: 1;
		padding: 10px;
		border: 1px solid #ddd;
		border-radius: 5px;
		font-size: 14px;
	}

	.pickercustomer {
		flex-grow: 1;
		border: 1px solid #ddd;
		border-radius: 5px;
		padding: 10px;
		font-size: 14px;
		width: 280px;
	}

	.pickerproduct {
		flex-grow: 1;
		border: 1px solid #ddd;
		border-radius: 5px;
		padding: 10px;
		font-size: 14px;
		width: 270px;
	}

	.picker-view {
		flex-grow: 1;
		border: 1px solid #ddd;
		border-radius: 5px;
		padding: 10px;
		font-size: 14px;
		width: 250px;
	}

	.picker {
		flex-grow: 1;
		border: 1px solid #ef5815;
		border-radius: 5px;
		padding: 10px;
		font-size: 14px;
		width: 250px;
	}

	.form-textarea {
		flex-grow: 1;
		padding: 10px;
		border: 1px solid #ddd;
		border-radius: 5px;
		font-size: 14px;
	}

	.product-list-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.add-product-button {
		background-color: #1aad19;
		color: #fff;
		border: none;
		border-radius: 5px;
		font-size: 14px;
		height: 20px;
		width: 100px;
		line-height: 20px;
		/* 垂直居中 */
		text-align: center;
	}

	.product-list {
		margin-top: 2px;
	}

	.product-item {
		border: 1px solid #ddd;
		border-radius: 5px;
		padding: 10px;
		background-color: #fff;
		margin-bottom: 10px;
	}

	.product-item-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 5px 0;
		border-bottom: 1px solid #eee;
	}

	.product-item-row:last-child {
		border-bottom: none;
	}

	.delete-button {
		background-color: #ff4d4f;
		color: #fff;
		border: none;
		border-radius: 5px;
		font-size: 12px;
		height: 20px;
		width: 90px;
		line-height: 20px;
		/* 垂直居中 */
		text-align: center;
	}

	.submit-button {
		margin-top: 10px;
		/* padding: 10px 20px; */
		background-color: #1890ff;
		color: #fff;
		border: none;
		border-radius: 5px;
		font-size: 14px;
		/* height: 20px; */
		width: 300px;
		/* line-height: 20px; */
		/* 垂直居中 */
		text-align: center;
	}
</style>